import { mapState } from 'vuex'

export default {
  component: {},
  data() {
    return {
      menus: [],
      collapsed: false,
      currentMenu: {},
      /**
       * BODY区域打开页面
       */
      bodyRegion: {
        view: null,
        params: null
      },
      /**
       * TAB栏打开页面
       */
      tabs: [],
      currTab: '',
      /**
       * 右滑面板打开页面
       */
      rightPanel: {
        width: 720,
        height: this.clientHeight - 55,
        visible: false,
        view: null,
        params: null,
        title: ''
      },
      searchLoading: false,
      refreshWindowSize: window.$debounce(this._refreshWindowSize, 500)
    };
  },
  computed: {
    ...mapState('ctx', {
      windowSize: 'windowSize',
      pageEvent: 'pageEvent',
      actionEndEvent: 'actionEndEvent',
    }),
    clientWidth() {
      return this.windowSize.clientWidth;
    },
    clientHeight() {
      return this.windowSize.clientHeight;
    },
    bodyHeight() {
      return this.windowSize.bodyHeight;
    },
    bodyWidth() {
      return this.windowSize.bodyWidth;
    },
    tenantInfo() {
      return this.$tenantInfo || {}
    },
    tenantName() {
      return this.tenantInfo ? this.tenantInfo.tenantName : ''
    },
    systemName() {
      return this.tenantInfo ? this.tenantInfo.systemName : '';
    },
    loginInfo() {
      return this.$loginInfo || {}
    },
    orgName() {
      return this.loginInfo.orgFullName || this.loginInfo.orgName || ''
    },
    username() {
      return this.loginInfo.username || ''
    },
    realName() {
      return this.loginInfo.name || ''
    },
  },
  activated() {
  },
  mounted() {
    this.init()
  },
  watch: {
    '$route.path': function () {
      this.changeRoute()
    },
    'windowSize.clientWidth': function() {
      this.initLeftCollapse()
    },
    pageEvent(e) {
      this.doOpenPage(e)
    },
    actionEndEvent(e) {
      this.doActionEnd(e)
    },
  },
  methods: {
    init() {
      this.refreshWindowSize()
      this.menus = this.loginInfo.menuTree || []
      this.initLeftCollapse()
      this.changeRoute()
    },
    initLeftCollapse() {
      if (this.windowSize.clientWidth < 1280) {
        this.collapsed = true
      } else {
        this.collapsed = false
      }
      this.refreshWindowSize()
    },
    changeRoute() {
      this.currTab = '0'
      this.tabs = []
      let { path } = this.$route
      if (path.endsWith('/')) {
        path = path.substring(0, path.length - 1)
      }
      this.bodyRegion.view = null
      // 获取功能页面
      const menu = this.findMenu(this.menus, path)
      let menuPage, menuFormPage
      if (menu && menu.path) {
        menuPage = menu.page ? menu.page : menu.path
        menuFormPage = path.substring(menu.path.length);
        if (menuPage.startsWith('/desktop')) {
          menuPage = menuPage.substring(8)
        }
      }
      // 获取路由中的参数
      let id = this.$route.query['id']
      let tab = this.$route.query['tab']
      let params = this.$route.query['params']
      if (params) {
        params = JSON.parse(params)
      }
      if (params) {
        params.id = id
      } else {
        params = {id: id}
      }
      // 打开页面
      console.log('changeRoute: menuPage = ', menuPage)
      console.log('changeRoute: menuFormPage = ', menuFormPage)
      if (menuFormPage) {
        menuFormPage = menuPage + menuFormPage
        if (tab) {
          this.tabs.push({
            label: tab || '',
            view: () => import('@/views' + menuFormPage),
            params: params,
            closable:  false
          })
        } else {
          this.bodyRegion.view = () => import('@/views' + menuFormPage)
          this.bodyRegion.params = params
        }
      } else if (menuPage) {
        this.tabs.push({
          label: menu.name,
          view: () => import('@/views' + menuPage),
          params: params,
        })
      } else {
        if (path.startsWith('/desktop')) {
          path = path.substring(8)
        }
        if (tab) {
          this.tabs.push({
            label: tab || '',
            view: () => import('@/views' + path),
            params: params,
            closable:  false
          })
        } else {
          this.bodyRegion.view = () => import('@/views' + path)
          this.bodyRegion.params = params
        }
      }
    },
    doOpenPage(event) {
      console.log('doOpenPage: %s', JSON.stringify(event))
      let pos = event.pos
      if (this.bodyRegion.view) {
        pos = 'rp'
      }
      if (pos === 'rp') {
        this.rightPanel.view = () => import('@/views' + event.path)
        this.rightPanel.params = event.params
        this.rightPanel.visible = true
        this.rightPanel.title = event.title
        this.rightPanel.height = this.clientHeight - 55
      } else {
        this.tabs.push({
          label: event.title,
          view: () => import('@/views' + event.path),
          params: event.params,
          closable: true,
        })
        this.currTab = '' + (this.tabs.length - 1)
      }
    },
    doActionEnd() {
      if (this.bodyRegion.view) {
        this.rightPanel.visible = false
      } else {
        const index = parseInt(this.currTab)
        let tab = this.tabs[index]
        if (tab.closable) {
          this.tabs.splice(index, 1)
          this.currTab = '' + (index - 1)
        }
      }
    },
    findMenu(menus, path) {
      for(let menu of menus) {
        if (path.indexOf(menu.path) == 0) {
          return menu
        } else if (menu.children) {
          const child = this.findMenu(menu.children, path)
          if (child) {
            return child
          }
        }
      }
      return null
    },
    doClickMenu(menu) {
      if (menu.path) {
        this.$router.replace(menu.path)
      }
    },
    doSearch(value) {
      if (!value) {
        this.$message.info('请输入检索关键字！')
        return
      }
      this.searchLoading = true
      this.$message.info('检索(' + value + ')，功能开发中...')
      setTimeout(() => {
        this.searchLoading = false
      }, 5000)
    },
    doMyDocument() {
      this.$message.info('开发中...')
    },
    doUpdatePassword() {
      this.$router.replace('/desktop/common/updatePassword')
    },
    doLogout() {
      sessionStorage.removeItem('LOGIN_INFO')
      sessionStorage.removeItem('LOGIN_TOKEN')
      // sessionStorage.removeItem('TENANT_ID')
      // sessionStorage.removeItem('TENANT_INFO')
      this.$router.replace('/login')
    },
    doLeftCollapse() {
      this.collapsed = !this.collapsed
      this.refreshWindowSize()
    },
    doTabRemove(name) {
      const index = parseInt(name)
      this.tabs.splice(index, 1)
      if (name === this.currTab) {
        this.currTab = '0'
      }
    },
    _refreshWindowSize() {
      this.$store.dispatch('ctx/refreshWindowSize')
    }
  }
};
